package com.zoro.barn.commons.webcommons.interceptors;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.zoro.barn.commons.tools.json.JsonUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.InputStream;

/**
 * 打印请求日志，可以在logback 中配置打印哪个请求的请求日志
 *
 * @author zhaoxingwu
 */
public class LogInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            String uri = request.getRequestURI();
            Logger thisLogger = LoggerFactory.getLogger(uri);
            if (thisLogger.isInfoEnabled()) {
                thisLogger.info("REQUEST  :  uri {}, method {}, contentType {}, parameter {}", uri, request.getMethod(),
                        request.getContentType(), getParam(request));
            }
        } catch (Exception e) {
            String handlerName = handler.toString();
            logger.error("error occurred when log request, handler :" + handlerName + ", error message:" + e.getMessage());
        }

        return true;
    }

    private String getParam(HttpServletRequest request) throws IOException {
        if (StringUtils.isNotBlank(request.getMethod())) {

            if (HttpMethod.GET == HttpMethod.valueOf(request.getMethod())) {
                return request.getQueryString();
            }

            if (HttpMethod.POST == HttpMethod.valueOf(request.getMethod())) {
                String contentType = request.getContentType();
                if (StringUtils.contains(contentType, MediaType.APPLICATION_JSON_VALUE)) {
                    return getJsonParam(request);
                }

                if (StringUtils.contains(contentType, MediaType.APPLICATION_FORM_URLENCODED_VALUE)) {
                    return getFormParam(request);
                }
            }
        }
        return null;
    }

    private String getJsonParam(HttpServletRequest request) throws IOException {

        InputStream is = request.getInputStream();
        ObjectNode objectNode = JsonUtil.readJsonObject(is);
        return objectNode.toString();
    }

    public String getFormParam(HttpServletRequest request) throws IOException {
        InputStream is = request.getInputStream();
        return new String(is.readAllBytes());
    }
}
